package com.huizhonglm.diap.ui.tab;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bruce.common.utils.EmptyUtil;
import com.bruce.pullrefresh.PullToRefreshBase;
import com.bruce.pullrefresh.PullToRefreshScrollView;
import com.huizhonglm.diap.R;
import com.huizhonglm.diap.api.model.app.banner.BannerInfo;
import com.huizhonglm.diap.api.model.shop.FeaturedBuyInfo;
import com.huizhonglm.diap.api.model.shop.ShopInfo;
import com.huizhonglm.diap.core.config.Constants;
import com.huizhonglm.diap.core.image.Thumb;
import com.huizhonglm.diap.core.location.LocationUtil;
import com.huizhonglm.diap.core.storage.model.LocationInfo;
import com.huizhonglm.diap.core.utils.DisplayUtil;
import com.huizhonglm.diap.core.utils.ToastUtil;
import com.huizhonglm.diap.core.utils.UserUtil;
import com.huizhonglm.diap.model.Shortcut;
import com.huizhonglm.diap.presenters.tab.TabhostHomePresenter;
import com.huizhonglm.diap.ui.BaseFragment;
import com.huizhonglm.diap.ui.app.BrowserActivity;
import com.huizhonglm.diap.ui.shop.SearchActivity;
import com.huizhonglm.diap.ui.shop.ShopDetailActivity;
import com.huizhonglm.diap.ui.shop.ShortcutShopActivity;
import com.huizhonglm.diap.ui.tab.iView.TabhostHomeIView;
import com.huizhonglm.diap.widget.Banner;
import com.huizhonglm.diap.widget.LoadView;
import com.huizhonglm.diap.widget.shortcuts.ShortcutsLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * 描述当前类的作用
 *
 * @author LiXiaoLong
 * @version 1.0
 * @since 2016-03-01 23:27
 */
public class TabhostHomeFragment extends BaseFragment implements TabhostHomeIView,
        LoadView.OnLoadAgainListener, AdapterView.OnItemClickListener, View.OnClickListener,
        ShortcutsLayout.OnShortcutItemClickListener, PullToRefreshBase.OnRefreshListener2<ScrollView> {
    private LayoutInflater mInflater;
    private View rootView;
    private Banner banner;
    private View bannerLv;
    private View featureBuyLabel;
    private View featureBuyScrl;
    private LinearLayout featureBuyView;
    private PullToRefreshScrollView pullView;
    private ListView listView;
    private LoadView loadView;
    private TextView cityTxt;
    private ImageButton title_shake_ibtn;

    private List<ShopInfo> mData;
    private TabhostHomeAdapter mAdapter;

    private TabhostHomePresenter mPresenter;

    private boolean isVisible = false;
    private boolean isPrepared = false;


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mPresenter = new TabhostHomePresenter(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        this.mInflater = inflater;
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_tabhost_home, container, false);
        }
        cityTxt = (TextView) rootView.findViewById(R.id.title_city_txt);
        TextView searchTxt = (TextView) rootView.findViewById(R.id.title_search_txt);
         title_shake_ibtn = (ImageButton) rootView.findViewById(R.id.title_shake_ibtn);
        ShortcutsLayout scLayout = (ShortcutsLayout) rootView.findViewById(R.id.shortcuts_layout);
        bannerLv = rootView.findViewById(R.id.banner_layout);
        banner = (Banner) rootView.findViewById(R.id.banner);
        featureBuyLabel = rootView.findViewById(R.id.featured_buy_txt);
        featureBuyScrl = rootView.findViewById(R.id.feature_buy_scrl);
        featureBuyView = (LinearLayout) rootView.findViewById(R.id.feature_buy_list_layout);
        loadView = (LoadView) rootView.findViewById(R.id.load_view);
        listView = (ListView) rootView.findViewById(R.id.home_shop_list);
        pullView = (PullToRefreshScrollView) rootView.findViewById(R.id.pull_to_refresh_scrl);
        pullView.setMode(PullToRefreshBase.Mode.BOTH);
        pullView.setOnRefreshListener(this);
        loadView.setDataView(pullView, this);
        listView.setOnItemClickListener(this);
        searchTxt.setOnClickListener(this);
        title_shake_ibtn.setOnClickListener(this);
        if (UserUtil.isLogin()){
            title_shake_ibtn.setVisibility(View.VISIBLE);
        }else{
            title_shake_ibtn.setVisibility(View.GONE);
        }

        float screenWidth = DisplayUtil.getWidth();
        float bannerHeight = screenWidth * 400f / 990f;
        banner.onCreateView();
        banner.setBannerSize(screenWidth, bannerHeight);
        scLayout.onCreate(mPresenter.loadShortcuts());
        scLayout.setOnShortcutItemClickListener(this);

        isPrepared = true;
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        onVisible();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        boolean userVisibleHint = getUserVisibleHint();
        if (userVisibleHint) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
        }
        if (title_shake_ibtn!=null){
            if (UserUtil.isLogin()){
                title_shake_ibtn.setVisibility(View.VISIBLE);
            }else{
                title_shake_ibtn.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onVisible() {
        if (isPrepared && isVisible) {
            setCityName(LocationUtil.getLocation());
            onLoadAgain();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ShopInfo shop = (ShopInfo) parent.getAdapter().getItem(position);
        if (shop != null) {
            Intent intent = new Intent(getActivity(), ShopDetailActivity.class);
            intent.putExtra("shopId", shop.getSid());
            startActivity(intent);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_search_txt:
                startActivity(new Intent(getActivity(), SearchActivity.class));
                break;
            case R.id.title_shake_ibtn:
                //startActivity(new Intent(getActivity(), ShakeActivityCapture.class));
                String shareString="惠众联盟带您畅游互联网+的新体验！\nhttp://www.huizhonglm.com/mobile/share/doShare?userId="+UserUtil.getUserId();
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT,shareString);
                sendIntent.setType("text/plain");
                startActivity(sendIntent);
                break;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        mPresenter.loadShopList(Constants.LOAD_DROP);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        mPresenter.loadShopList(Constants.LOAD_MORE);
    }

    @Override
    public void onLoadAgain() {
        mPresenter.loadBanner();
        mPresenter.loadFeaturedBuy();
        mPresenter.loadShopList(Constants.LOAD_INIT);
    }

    @Override
    public void onShortcutItemClick(Shortcut entity) {
        if (entity != null) {
            Intent intent = new Intent(getActivity(), ShortcutShopActivity.class);
            intent.putExtra("categoryId", entity.getId());
            intent.putExtra("categoryName", entity.getName());
            startActivity(intent);
        }
    }

    @Override
    public void onLoadBannerSuccess(List<BannerInfo> data) {
        if (!EmptyUtil.isEmpty(data)) {
            initBanner(data);
        } else {
            bannerLv.setVisibility(View.GONE);
        }
    }

    @Override
    public void onLoadBannerFailure() {
        bannerLv.setVisibility(View.GONE);
    }

    @Override
    public void onLoadFeaturedBuySuccess(List<FeaturedBuyInfo> data) {
        if (!EmptyUtil.isEmpty(data)) {
            featureBuyScrl.setVisibility(View.VISIBLE);
            featureBuyLabel.setVisibility(View.VISIBLE);
            initFeatureView(data);
        } else {
            featureBuyScrl.setVisibility(View.GONE);
            featureBuyLabel.setVisibility(View.GONE);
        }
    }

    @Override
    public void onLoadFeaturedBuyFailure() {
        featureBuyScrl.setVisibility(View.GONE);
        featureBuyLabel.setVisibility(View.GONE);
    }

    @Override
    public void onLoadShopListSuccess(String pullFlag, List<ShopInfo> data) {
        switch (pullFlag) {
            case Constants.LOAD_INIT:
                this.mData = data;
                updatePage(data);
                loadView.showDataView();
                break;
            case Constants.LOAD_DROP:
                this.mData = data;
                updatePage(data);
                pullView.onRefreshComplete();
                break;
            case Constants.LOAD_MORE:
                this.mData.addAll(data);
                updatePage(data);
                pullView.onRefreshComplete();
                break;
        }
    }

    @Override
    public void onLoadShopListFailure(String pullFlag) {
        switch (pullFlag) {
            case Constants.LOAD_INIT:
                loadView.showErrorView();
                break;
            case Constants.LOAD_DROP:
                ToastUtil.makeTextShort("刷新失败");
                pullView.onRefreshComplete();
                break;
            case Constants.LOAD_MORE:
                ToastUtil.makeTextShort("加载更多失败");
                pullView.onRefreshComplete();
                break;
        }
    }

    public void setLocationCity(LocationInfo info){
        if (isPrepared && isVisible) {
            setCityName(info);
            loadView.showProgress();
            onLoadAgain();
        }

    }

    private void setCityName(LocationInfo info){
        if (cityTxt != null) {
            if (info != null && info.getCity() != null && !info.getCity().equals("")) {
                cityTxt.setText(info.getCity().replace("市", " "));
            } else {
                cityTxt.setText("定位失败 ");
            }
        }
    }

    private void updatePage(List<ShopInfo> data){
        setPullViewMode(data);
        if (mAdapter == null) {
            mAdapter = new TabhostHomeAdapter(mInflater, mData);
            listView.setAdapter(mAdapter);
        } else {
            mAdapter.setData(mData);
            mAdapter.notifyDataSetChanged();
        }
    }

    private void setPullViewMode(List<ShopInfo> data){
        if (!EmptyUtil.isEmpty(data)) {
            if (mData.size() >= Constants.PAGE_SIZE) {
                if (data.size() < Constants.PAGE_SIZE) {
                    pullView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                } else {
                    pullView.setMode(PullToRefreshBase.Mode.BOTH);
                }
            } else {
                pullView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
            }
        }
    }

    private void initBanner(List<BannerInfo> data){
        if (data != null && data.size() > 0) {
            bannerLv.setVisibility(View.VISIBLE);
            List<ImageView> views = new ArrayList<>();
            // 将最后一个ImageView添加进来
            views.add(getBannerImage(data.get(data.size() - 1)));
            for (int i = 0; i < data.size(); i++) {
                views.add(getBannerImage(data.get(i)));
            }
            // 将第一个ImageView添加进来
            views.add(getBannerImage(data.get(0)));
            // 设置循环，在调用setData方法前调用
            banner.setCycle(true);
            // 在加载数据前设置是否循环
            banner.setData(views, new Banner.OnBannerClickListener() {

                @Override
                public void onBannerClick(int position, View imageView) {
                    if (banner.isCycle()) {
                        BannerInfo info = (BannerInfo) imageView.getTag();
                        if (info != null) {
                            if ("0".equals(info.getType())) {
                                String url=info.getActiveUrl()+"?userId=0";
                                if (!TextUtils.isEmpty(UserUtil.getUserId())){
                                    url=info.getActiveUrl()+"?userId="+UserUtil.getUserId();
                                }
                                Intent browser = new Intent(getActivity(), BrowserActivity.class);
                                browser.putExtra("webTitle", info.getActiveTitle());
                                browser.putExtra("webAddress", url);
                                startActivity(browser);
                            } else if ("1".equals(info.getType())) {
                                Intent shopDtl = new Intent(getActivity(), ShopDetailActivity.class);
                                shopDtl.putExtra("shopId", info.getShopId());
                                startActivity(shopDtl);
                            } else {
                                ToastUtil.makeTextShort("当前图片无跳转");
                            }
                        }
                    }
                }
            });

            //设置轮播
            if (data.size() > 1){
                banner.setWheel(true);
                banner.setTime(7000);
            } else {
                banner.setWheel(false);
            }
            //设置圆点指示图标组居中显示，默认靠右
            banner.setIndicatorCenter();
        } else {
            bannerLv.setVisibility(View.GONE);
        }
    }

    private ImageView getBannerImage(BannerInfo info) {
        ImageView image = (ImageView)mInflater.inflate(R.layout.item_banner_image, null);
        image.setTag(info);
        Thumb.getInstance().display(image, info.getImageUrl(), R.drawable.def_banner);
        return image;
    }

    private void initFeatureView(List<FeaturedBuyInfo> data){
        int wrapContent = LinearLayout.LayoutParams.WRAP_CONTENT;
        LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(wrapContent, wrapContent);
        featureBuyView.removeAllViews();
        for (FeaturedBuyInfo info : data) {
            featureBuyView.addView(getFeatureItem(info), llp);
        }
    }

    private View getFeatureItem(final FeaturedBuyInfo info){
        View item = mInflater.inflate(R.layout.item_featured_buy, null);
        ImageView logo = (ImageView) item.findViewById(R.id.logo_img);
        TextView name = (TextView) item.findViewById(R.id.name_txt);

        Thumb.getInstance().display(logo, info.getPicPath(), R.drawable.def_logo);
        name.setText(info.getSpName());

        item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ShopDetailActivity.class);
                intent.putExtra("shopId", info.getSid());
                startActivity(intent);
            }
        });
        return item;
    }
}
